<?php
//+-----------------------------------------------------------
//| 人生是荒芜的旅行，冷暖自知，苦乐在心
//+-----------------------------------------------------------
//| Author:Janmas <janmas@126.com>
//+-----------------------------------------------------------
//| 
//+-----------------------------------------------------------

namespace app\admin\model;


use app\admin\exception\LogicException;
use think\Model;
use think\model\concern\SoftDelete;

class Menu extends AdminModel
{

    use SoftDelete;

    /**
     * 菜单类型
     * @var array[]
     */
    public $menuType = [
        [
            'name'    => '菜单组' ,
            'checked' => false ,
            'flag'    => 0
        ] ,
        [
            'name'    => '菜单' ,
            'checked' => true ,
            'flag'    => 1
        ] ,
        [
            'name'    => '按钮' ,
            'checked' => false ,
            'flag'    => 2
        ]
    ];

    protected $name = 'system_menu';

    protected $autoWriteTimestamp = true;

    protected $deleteTime = 'deletetime';

    protected $defaultSoftDelete = null;

    protected $createTime = 'createtime';

    protected $updateTime = 'updatetime';

    protected $schema = [
        'id'         => 'int' ,
        'name'       => 'string' ,
        'icon'       => 'string' ,
        'is_pic'     => 'int' ,
        'pid'        => 'int' ,
        'sort'       => 'int' ,//0~9999 正序排列
        'deletetime' => 'int' ,
        'createtime' => 'int' ,
        'updatetime' => 'int' ,
        'link'       => 'string' ,
        'controller' => 'string' ,
        'action'     => 'string' ,
        'type'       => 'int' ,
        'is_show'    => 'int' ,
        'flag'       => 'string'
    ];

    protected $submitField = [
        'name'       => 'string' ,
        'icon'       => 'string' ,
        'pid'        => 'int' ,
        'sort'       => 'int' ,
        'link'       => 'string' ,
        'is_show'    => 'int' ,
        'controller' => 'string' ,
        'action'     => 'string' ,
        'type'       => 'int' ,
        'flag'       => 'string' ,
    ];

    protected $append = [
        'flag_name',
    ];

    public static function onBeforeInsert ( Model $model )
    {
        if(empty($model->controller) && empty($model->action)){
            return true;
        }
        /**
         * 检查控制器、方法有没有重复
         */
        $menu = self::where([ 'controller' => $model->controller , 'action' => $model->action ])->findOrEmpty();
        if ( !$menu->isEmpty() ) {
            throw new LogicException('该路径已被占用,菜单名:' . $menu['name']);
        }
    }

    public static function onBeforeUpdate ( Model $model )
    {
        $menu = self::where([ 'controller' => $model->controller , 'action' => $model->action ])->findOrEmpty();
        if ( !$menu->isEmpty() && input('id/d') !== $menu->id ) {
            throw new LogicException('该路径已被占用,菜单名:' . $menu['name']);
        }
    }

    public static function onAfterInsert ( $menu )
    {
        if ( !env('app_debug') ) {
            $self = ( new self );
            $self->getTreeMenu(true);
            $self->getTreeComponets(true);
        }
    }

    public static function onAfterUpdate ( $menu )
    {
        if ( !env('app_debug') ) {
            $self = ( new self );
            $self->getTreeMenu(true);
            $self->getTreeComponets(true);
        }
    }

    public static function onAfterDelete ( $menu )
    {
        if ( !env('app_debug') ) {
            $self = ( new self );
            $self->getTreeMenu(true);
            $self->getTreeComponets(true);
        }
    }

    public function scopeDeleted ( $query , $dt = true )
    {
        if ( !$dt ) {
            $query->whereNull('deletetime');
        }
        else {
            $query->whereNotNull('deletetime');
        }
    }

    public function scopeShow ( $query , $show = true )
    {
        if ( !$show ) {
            $query->where('is_show' , 0);
        }
        else {
            $query->where('is_show' , 1);
        }
    }

    /**
     * 获取各个模块的树形菜单
     * @param false $isForced
     * @return array|mixed|object|\think\App
     */
    public function getTreeMenu ( $isForced = false )
    {
    	$module = app('http')->getName();
        if ( cache('?menu_'.$module) && !$isForced ) {
            return cache('menu_'.$module);
        }

        $menu = self::show()->field('id,pid,name,icon,sort,link,flag')->where('flag',$module)->order('sort asc')->select();
        if ( $menu ) {
            $tree = recursion($menu->toArray());
            if ( !env('app_debug') ) {
                cache('menu_'.$module , $tree);
            }
            return $tree;
        }
        else {
            return [];
        }
    }

    /**
     * 获取所有的树形菜单
     * @param false $isForced
     * @return array|mixed|object|\think\App
     */
    public function getTreeComponets ( $isForced = false )
    {
        if ( cache('?tree') && !$isForced ) {
            return cache('tree');
        }

        $menu = self::show()->field('id,pid,name as title,sort')->order('sort asc')->select();
        if ( $menu ) {
            $menu = $menu->toArray();
            foreach ( $menu as &$value ) {
                $value['field'] = 'permession[]';
            }
            $tree = recursion($menu);
            if ( !env('app_debug') ) {
                cache('tree' , $tree);
            }
            return $tree;
        }
        else {
            return [];
        }
    }

    protected function setAttrLink ( $data )
    {
        if ( !empty($data['action']) ) {
            return $data['controller'] . '/' . $data['action'];
        }
        return '';
    }

    protected function setAttrIsShow ( $data )
    {
        if ( isset($data['is_show']) )
            return 1;
        else
            return 0;
    }

    protected function setAttrFlag ( $data )
    {
    	if($data['pid'] > 0){
    		return  self::where('id',$data['pid'])->value('flag');
	    }

        if ( !isset($data['flag']) ) {
            return 'admin';
        }
        return $data['flag'];
    }

    /**
     * 获取角色、
     * @return \think\model\relation\BelongsToMany
     */
    public function permession ()
    {
        return $this->belongsToMany(Role::class , Permession::class , 'permession_id' , 'role_id');
    }

    public function getFlagNameAttr($value,$data){
        if(isset($data['flag'])){
            if($data['flag'] == 'admin'){
                return '系统模块&nbsp;[admin]';
            }
            return Plugin::where('flag',$data['flag'])->value('name').'&nbsp;['.$data['flag'].']';
        }

    }
}